package com.kanshu.ksgb.fastread.doudou.common.net.rx;

import android.text.TextUtils;

import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


/**
 * Created by wcy on 2017\6\14 0014.
 */

public abstract class BaseObserver<T> implements Observer<BaseResult<T>> {
    protected Disposable mDisposable;
    @Override
    public void onSubscribe(Disposable d) {
        mDisposable = d;
    }
    @Override
    public void onNext(BaseResult<T> tBaseResult) {
        if (tBaseResult.result != null && tBaseResult.result.status != null) {
            if (tBaseResult.result.status.code == 0) {
                onResponse(tBaseResult, tBaseResult.result.data, mDisposable);
            } else {
                onError(tBaseResult.result.status.code, tBaseResult.result.status.msg);
            }
        } else {
            onError(Constants.ErrCode.NoData, "no data");
        }
    }

    @Override
    public void onError(Throwable e) {
        String s = "";
        if (e == null || TextUtils.isEmpty(e.getMessage())) {
            s = "error";
        } else {
            e.printStackTrace();
        }
        onError(Constants.ErrCode.NetErr, s);
    }
    @Override
    public void onComplete() {
        onFinish();
    }
    public abstract void onResponse(BaseResult<T> tBaseResult, T t, Disposable disposable);
    public void onError(int code, String errDesc) {}
    public void onFinish() {}
}
